package tgc.edu.yzy.web.admin.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.Custom;
import tgc.edu.yzy.custom.DatagridUtils;
import tgc.edu.yzy.entity.User;
import tgc.edu.yzy.service.UserService;

@Controller
@RequestMapping(value="admin/user")
public class UserController {
	@Autowired
	private UserService userservice;
	@RequestMapping(value="index")
	private String index() {
		return "admin/user/index";
	}
	
	@RequestMapping(value="pagelist")
	@ResponseBody
	private Object pagelist(DatagridUtils form,User user,String sousuo) {
		Pageable pageable=form.buildPageable();
		Page<User> users=null;
		Specification<User> spec = new Specification<User>() {

			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				HashSet<Predicate> rules = new HashSet<>();
				if(StringUtils.hasText(user.getName())) {
					rules.add(criteriaBuilder.like(root.get("name"), "%"+user.getName()+"%"));
				}else if(StringUtils.hasText(user.getMynumber())) {
					rules.add(criteriaBuilder.like(root.get("mynumber"), "%"+user.getMynumber()+"%"));
				}else if(StringUtils.hasText(sousuo)) {
					rules.add(criteriaBuilder.equal(root.get("dapa").get("id"), sousuo));
				}
				
				return criteriaBuilder.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		users= userservice.findAll(spec,pageable);
		HashMap<String , Object> result = form.getPageResult(users);
		return result; 
	}
}
